package com.ycz;

import com.alibaba.fastjson.JSONObject;
import com.ycz.mapper.UserMapper;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author ycz
 * @date 2021/6/18
 */
public class MapperFactoryBean implements FactoryBean {

    private Class mappers;

    public MapperFactoryBean(Class mappers) {
        this.mappers = mappers;
    }

    @Override
    public Object getObject() throws Exception {
        // 创建接口对应的实例，通过接口生成实现接口的代理类
        Object o = Proxy.newProxyInstance(MapperFactoryBean.class.getClassLoader(), new Class[]{mappers}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println(method.getName());
                return null;
            }
        });
        return o;
    }

    @Override
    public Class<?> getObjectType() {
        return MapperFactoryBean.class;
    }

//
//    /**
//     * InvocationHandler扩展
//     */
//    public class MapperProxy implements InvocationHandler {
//
//        /**
//         * 代理的接口
//         */
//        private Class mappers;
//
//        public MapperProxy(Class mappers) {
//            this.mappers = mappers;
//        }
//
//        @Override
//        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//            System.out.println("mappers==" + mappers);
//            System.out.println("proxy==" + JSONObject.toJSONString(proxy));
//            System.out.println("method==" + method);
//            return null;
//        }
//    }

}
